<template>
    <div class="LoginView">
        <van-image round fit="cover" width="8.125rem" height="8.125rem" src="imges/ChatIcon.png"/>
        <From :select="select" :initApp="initApp" />
        <p @click="select = !select">
            {{ select ? "没有账号?注册点这里" : "返回登录" }}
        </p>
    </div>
</template>

<script>
    import { Toast, Notify } from "vant";
    import { mapActions, mapMutations } from "vuex";
    import From from "@/components/login/from.vue";
    import initListeners from "@/socket/listeners";

    export default {
        name: "LoginView",
        data() {
            return {
                select: true,
            };
        },
        components: {
            From,
        },
        methods: {
            ...mapMutations(["upUser", "upGroupChats", 'upFriend']),
            ...mapMutations('newFriend', ['upApplicationStatus', 'pushApplications']),
            ...mapActions('login', ['getFriends', 'getApplications', 'getGroupChats']),
            ...mapActions('newFriend', ['getApplications']),
            async initApp(value) {    // 初始化 app                
                if (value.status_code != 200) {
                    Toast.clear();
                    Toast({ icon: "fail", message: value.info });
                    this.tel = "";
                    return;
                }
                this.upUser(value.data);
                Toast.clear();

                let res_friends = await this.getFriends(value.data.phone);  // 获取好友
                if (res_friends.status_code != 200) {
                    Toast.fail(`好友获取失败: ${res_friends.error}`);  
                    return
                }   
                let arr = [];
                res_friends.friends.forEach(item => arr.push(item))
                this.upFriend(arr); // 更新好友列表

                let res_applications =  await this.getApplications(value.data.phone);   // 获取好友申请
                this.pushApplications(res_applications.data);

                let res_groupChats = await this.getGroupChats(value.data.phone);    // 获取群聊
                if (res_groupChats.status_code != 200)
                {
                    this.$toast(`status: ${ res_groupChats.status_code }, err: ${ res_groupChats.data }`);
                    return;
                }
                this.upGroupChats(res_groupChats.data); // 更新群聊列表

                initListeners();    // 初始化监听器

                this.$router.push("/message");
                Notify({ type: "success", duration: 700, message: "登录成功" });
            },
        },
    };
</script>

<style lang="less" scoped>
    .LoginView {
        padding-top: 7.5rem;
        .van-image {
            display: block;
            margin: 0 auto .625rem auto;
        }
        p {
            margin-top: 2.5rem;
            font-size: 0.8125rem;
            text-decoration: underline;
            text-align: center;
            &:select {
                color: chocolate;
            }
        }
    }
</style>
